/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.find.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.find.entity.Ads;
import com.thinkgem.jeesite.modules.find.service.AdsService;

/**
 * 广告管理Controller
 * @author 罗洪州
 * @version 2018-02-08
 */
@Controller
@RequestMapping(value = "${adminPath}/find/ads")
public class AdsController extends BaseController {

	@Autowired
	private AdsService adsService;
	
	@ModelAttribute
	public Ads get(@RequestParam(required=false) String id) {
		Ads entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = adsService.get(id);
		}
		if (entity == null){
			entity = new Ads();
		}
		return entity;
	}
	
	@RequiresPermissions("find:ads:view")
	@RequestMapping(value = {"list", ""})
	public String list(Ads ads, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Ads> page = adsService.findPage(new Page<Ads>(request, response), ads); 
		model.addAttribute("page", page);
		return "modules/find/adsList";
	}

	@RequiresPermissions("find:ads:view")
	@RequestMapping(value = "form")
	public String form(Ads ads, Model model) {
		model.addAttribute("ads", ads);
		return "modules/find/adsForm";
	}

	@RequiresPermissions("find:ads:edit")
	@RequestMapping(value = "save")
	public String save(Ads ads, Model model, RedirectAttributes redirectAttributes) {
        ads.setContent(StringEscapeUtils.unescapeHtml4(ads.getContent().trim()));
        if(!(StringUtils.isEmpty(ads.getImg()) || ads.getImg().contains("http://"))) {
            ads.setImg( Global.CURRENT_SERVER+ads.getImg() );
        }
        if (!beanValidator(model, ads)){
			return form(ads, model);
		}
		adsService.save(ads);
		addMessage(redirectAttributes, "保存广告成功");
		return "redirect:"+Global.getAdminPath()+"/find/ads/?repage";
	}
	
	@RequiresPermissions("find:ads:edit")
	@RequestMapping(value = "delete")
	public String delete(Ads ads, RedirectAttributes redirectAttributes) {
		adsService.delete(ads);
		addMessage(redirectAttributes, "删除广告成功");
		return "redirect:"+Global.getAdminPath()+"/find/ads/?repage";
	}

}